package com.tanhua.server.service;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.FriendApi;
import com.tanhua.dubbo.api.mongo.SimilarYouApi;
import com.tanhua.dubbo.api.mongo.UserLikeApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Report;
import com.tanhua.model.mongo.SimilarYou;
import com.tanhua.model.mongo.UserLike;
import org.apache.commons.collections.ListUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SimilarYouService {
    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private SimilarYouApi similarYouApi;

    @DubboReference
    private UserLikeApi userLikeApi;

    @DubboReference
    private FriendApi friendApi;

    public List<SimilarYou> findSimilarYouList(Long currentUserId) {

        //查找本机用户的好友Id
        List<Friend> friendList = friendApi.getAllFriend(currentUserId);
        List<Long> friendIds = friendList.stream().map(Friend::getFriendId).collect(Collectors.toList());
        //查找本机用户不喜欢的Id
        List<UserLike> userLikes = userLikeApi.exist(currentUserId);
        List<Long> dislikeIds = userLikes.stream().map(UserLike::getLikeUserId).collect(Collectors.toList());
        //合并需要排除的用户Id
        List<Long> excludeIds = ListUtils.union(dislikeIds, friendIds);

        //查询相似者报告
        List<Report> reports = similarYouApi.findReportUserIds(currentUserId,excludeIds);

        //2.2判断相似者的报告是否成在
        if (CollectionUtils.isEmpty(reports)){
            return null;
        }

        //2.3根据相似者的报告id获取用户信息
        List<Long> userIds = reports.stream().map(report -> report.getUserId()).distinct().collect(Collectors.toList());
        List<SimilarYou> similarYouList = new ArrayList<>();
        UserInfo currentUserInfo = userInfoApi.getById(currentUserId);
        for (Long userId : userIds) {
            UserInfo userInfo = userInfoApi.getById(userId);
            if (!currentUserInfo.getGender().equals(userInfo.getGender())){  //如果相似者的性别和当前用户性别不同，则加入相似者列表
                SimilarYou similarYou = SimilarYou.init(userInfo);
                similarYouList.add(similarYou);
            }
//            SimilarYou similarYou = SimilarYou.init(userInfo);
//            similarYouList.add(similarYou);
        }
        //3.返回相似者的列表信息
        return similarYouList;
    }
}
